<?php

class storeController extends manageController {
    # 测试饿了么开发参数
    const SANDBOX_KEY = '7sU488MRSH';
    const SANDBOX_SECRET = '69be1d5920ed4738c23f0750f69f29a44a00360f';

    # 正式饿了么开发参数
    const KEY = 'Of3uIZzKD7';
    const SECRET = '4ef3a27e7d724a127b80ead9320f0ee210f485f3';

    # 饿了么 沙箱 + 正式 【暂弃用】
    const SANDBOX_URL = 'https://open-api-sandbox.shop.ele.me/api/v1/';
    const ELM_URL = 'https://open-api.shop.ele.me/api/v1/';


    # 饿了么 沙箱 + 正式 获取TOKEN 地址
    const ELM_SANDBOX_TOKEN_URL = 'https://open-api-sandbox.shop.ele.me/token';
    const ELM_TOKEN_URL = 'https://open-api.shop.ele.me/token';

    # 回调地址  必须为https（上线后）
    const JT_TEST_URL = 'http://zhaipei.shjieta.com.cn/';
    const ZP_URL = 'https://zhaipei.ganso.com.cn';
    # 正式环境：token：30天，refresh_token：35天。

    public function __construct() {
        if (!isset($_SESSION['zp_manage']['islogin']) || empty($_SESSION['zp_manage']['islogin'])) {
            Tools::AlertTxt('?md=manage&cl=login&at=login', '请先登录');
            exit;
        }
    }


    public function storelistAction() {
        $table = "xd_store";
        $func = (!empty($this->params['func'])) ? $this->params['func'] : '';
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);

        $query = (!empty($this->params['query'])) ? $this->params['query'] : '';
        $fcompany = (!empty($this->params['fcompany'])) ? $this->params['fcompany'] : '';
        $business_status= (!empty($this->params['business_status'])) ? $this->params['business_status'] : '';
        $elm_query= (!empty($this->params['elm_query'])) ? $this->params['elm_query'] : '';
        $query = urldecode($query);
        $this->view->setVariable("query", $query);
        $this->view->setVariable("fcompany", $fcompany);
        $this->view->setVariable("elm_query", $elm_query);

        //上下線
        if (!empty($func) && $func == "status") {
            $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
            if ($id > 0) {
                $where_fields = array("AND" => array("=" => array("id" => $id)));
                $row = $this->model->getItemById($id, $table);
                $field = array();

                $field['zp_status'] = $row['zp_status'] == '1' ? '0' : '1';
                $field['editor'] = $_SESSION['zp_manage']['uid'];
                $field['updatedt'] = 'now()';
//                var_dump($_SESSION['zp_manage']['uid']);
//                var_dump($field);die;

                $r = $this->model->updateItem($field, $where_fields, $table);

                //日志
                $log = array();
                $log['table_id'] = $id;
                $log['table_name'] = $table;
                $log['type'] = 4;
                $log['page'] = "账号上下线";
                $log['content'] = $log['page'] . "：" . $this->params["id"];
                $org = array();
                $field1 = array();
                $this->model->setLog($log, $org, $field1);
            }
            echo json_encode(array('status'=>1),JSON_UNESCAPED_UNICODE);
            exit;
        }

        //抓列表
        $where = "a.isdeleted = 0 ";
        if (!empty($query)) {
            $where .= " AND a.store_id like '%$query%' OR a.storename like '%$query%'";
        }

       if (!empty($elm_query)) {
                $where .= " AND a.elm_shop_id = $elm_query";
            }

        if (!empty($fcompany)) {
            $where .= " AND b.name like '%$fcompany%'";
        }
        if (!empty($business_status)) {
            $where .= " AND a.business_status = $business_status";
        }

        $sql = "SELECT a.*,b.name FROM $table as a left join xd_company as b ON a.company_id = b.code WHERE $where  order by id asc";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $rsp_list = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);

        if (!empty($rsp_list)) {
            while ($row = mysqli_fetch_array($rsp_list, MYSQLI_ASSOC)) {
                $res[] = $row;
            }
        }
        $this->view->setVariable("business_status", $business_status);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function storelisteditAction(){
        $table = 'xd_store';
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $store_id = empty($this->params["store_id"]) ? '0' : (int) $this->params["store_id"];
        $phone = empty($this->params["phone"]) ? '0' : (int) $this->params["phone"];
//        $express_id = empty($this->params["express_id"]) ? '0' : $this->params["express_id"];
        $pwd = empty($this->params["pwd"]) ? '0' : $this->params["pwd"];
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        if($store_id){
            $field = $this->params["express"];

            if($pwd){
                $salt = Data::getSalt(20);
                $field['salt'] = $salt;
                $saltpwd = sha1($salt . $pwd);
                $field['password'] = $saltpwd;
            }

            $field['phone'] = $phone;
            $where_fields = array("AND" => array("=" => array("id" => $store_id)));
            $status = $this->model->updateItem($field, $where_fields, $table);
            if($status){
                $url = '?md=' . MvcReg::$_moduleName . '&cl=' . MvcReg::$_controllerName . '&at=storelist';
                $url .='&page='.$page;
                Tools::AlertTxt($url, $this->getKeyWord('SAVE') . $this->getKeyWord('Msg_Successful'));
            }else{
                $url = '?md=' . MvcReg::$_moduleName . '&cl=' . MvcReg::$_controllerName . '&at=storelist';
                $url .='&page='.$page;
                Tools::AlertTxt($url, $this->getKeyWord('SAVE') . $this->getKeyWord('Msg_Successful'));
            }
        }
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);
        $row = $this->model->getItemById($id, 'xd_store');

        $this->view->setVariable("row", $row);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    /**
     * 饿了么绑定
     */
    public function elmAction(){
        $table = 'xd_store';
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $shop_id = empty($this->params["shop_id"]) ? '0' : (int) $this->params["shop_id"];
        $elm_shop_id = empty($this->params["elm_shop_id"]) ? '0' : $this->params["elm_shop_id"];
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $row = $this->model->getItemById($id, $table);

        if(!$row){
            $url = '?md=manage&cl=store&at=storelist';
            $url .='&page='.$page;
            Tools::AlertTxt($url, '店铺信息有误');
            exit;
        }
        $this->view->setVariable("shop_id", $shop_id);
        $this->view->setVariable("page", $page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }




    public function companyAction() {
        $table = "xd_company";
        $func = (!empty($this->params['func'])) ? $this->params['func'] : '';
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $query = (!empty($this->params['query'])) ? $this->params['query'] : '';
        $query = urldecode($query);


        //上下線
        if (!empty($func) && $func == "status") {
            $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
            if ($id > 0) {
                $where_fields = array("AND" => array("=" => array("id" => $id)));
                $row = $this->model->getItemById($id, $table);
                $field = array();

                $field['status'] = $row['status'] == '1' ? '0' : '1';
                $field['editor'] = $_SESSION['zp_manage']['uid'];
                $field['updatedt'] = 'now()';

                $r = $this->model->updateItem($field, $where_fields, $table);
                if($r){
                    if($field['status'] == 1)
                        $field_store['zp_status'] = 1;
                    else
                        $field_store['zp_status'] = 0;
                    $where_store = array("AND" => array("=" => array("company_id" => $row['code'])));
                    $field_store['editor'] = $_SESSION['zp_manage']['uid'];
                    $field_store['updatedt'] = 'now()';
                    $r = $this->model->updateItem($field_store, $where_store, 'xd_store');
                }

                //日志
                $log = array();
                $log['table_id'] = $id;
                $log['table_name'] = $table;
                $log['type'] = 4;
                $log['page'] = "账号上下线";
                $log['content'] = $log['page'] . "：" . $this->params["id"];
                $org = array();
                $field1 = array();
                $this->model->setLog($log, $org, $field1);
            }
            echo json_encode(array('status'=>1),JSON_UNESCAPED_UNICODE);
            exit;
        }
        //抓列表
        $where_fields = array("AND" => array("=" => array("isdeleted" => 0,'is_parent'=>1)));
        $like_fields = array();
        if (!empty($query)) {
            $like_fields = array('name' => $query,'code' => $query);
        }
        $orderby = array('id' => 'asc');
        $total_count = $this->model->getTotalCount($table, $where_fields, $like_fields);
        $rsp_list = $this->model->getAllByPage($page, $number_page, $where_fields, $table, $like_fields, $orderby);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);
        $this->view->setVariable("query", $query);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    public function companyeditAction(){
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        $row = $this->model->getItemById($id, 'xd_company');
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $companyData = $this->params["express"];
            $pwd = $this->params["pwd"];

           if(!empty($pwd)){
               $salt = Data::getSalt(20);
               $companyData['salt'] = $salt;
               $saltpwd = sha1($salt . $pwd);
               $companyData['password'] = $saltpwd;
           }
            $where_fields = array("AND" => array("=" => array("id" => $this->params['company_id'])));
            $returnId = $this->model->updateItem($companyData,$where_fields, 'xd_company');
            if($returnId){
                $url = '?md=' . MvcReg::$_moduleName . '&cl=' . MvcReg::$_controllerName . '&at=company';
                $url .='&page='.$page;
                Tools::AlertTxt($url, $this->getKeyWord('SAVE') . $this->getKeyWord('Msg_Successful'));
            }
            exit;
        }
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("row", $row);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }



    /**
     * 导出
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */
    public function exportAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $query = (!empty($this->params['query'])) ? $this->params['query'] : '';
        $where = 'isdeleted = 0 AND status = 1';
        if (!empty($query)) {
            $where .= " AND name like '%$query%' OR code like '%$query%'";
        }
        $sql = "SELECT * FROM xd_company  WHERE $where order by createdt desc ";
//        echo $sql; die;
        $rsp_list = $this->model->getAny($sql);
        if (!empty($rsp_list)) {
            while ($row = mysqli_fetch_array($rsp_list, MYSQLI_ASSOC)) {
                $res[] = $row;
            }
        }
        if($res && is_array($res) && count($res) > 0) {
            $titles = array('序号', '分司名称', '分司代码');
            $tableName = "订单列表";
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles)."\n";
            foreach ($res as $key => $row) {
                $k = $key + 1;
                $rows['id'] = $k;
                $rows['name'] = $row['name'];
                $rows['code'] = $row["code"];
                echo implode("\t ,", $rows) . "\n";
            }

            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:application/vnd.ms-excel');
            ob_end_flush();
            $log = array();
            $log['table_id'] = 0;
            $log['table_name'] = 'care';
            $log['type'] = 5;
            $log['page'] = $tableName;
            $log['content'] = $log['page'] . "：" . $tableName . ".csv";
            $org = array();
            $modify = array();
            $this->model->setLog($log, $org, $modify);
            exit;
        }else{
            Tools::AlertTxt('?md=manage&cl=store&at=company', '没有可汇出数据');
        }
    }

    /**
     * 导出 门店
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */
    public function exportStoreAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $query = (!empty($this->params['query'])) ? $this->params['query'] : '';
        $business_status = (!empty($this->params['business_status'])) ? $this->params['business_status'] : '';
        $fcompany = (!empty($this->params['fcompany'])) ? $this->params['fcompany'] : '';

        $where = "a.isdeleted = 0 ";
        if (!empty($query)) {
            $where .= " AND (a.store_id like '%$query%' OR a.storename like '%$query%')";
        }
        if (!empty($business_status)) {
            $where .= " AND a.business_status = $business_status";
        }
        if (!empty($fcompany)) {
            $where .= " AND b.name like '%$fcompany%'";
        }
        $sql = "SELECT a.*,b.name FROM xd_store as a left join xd_company as b ON a.company_id = b.code WHERE $where order by a.id asc";
        $rsp_list = $this->model->getAny($sql);
        $res = [];
        if (!empty($rsp_list)) {
            while ($row = mysqli_fetch_array($rsp_list, MYSQLI_ASSOC)) {
                $res[] = $row;
            }
        }
        if($res && is_array($res) && count($res) > 0) {
            $titles = array('序号', '门店编号', '分司名称', '门店名称', '电话', '地址', '状态');
            $tableName = "订单列表";
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles)."\n";
            foreach ($res as $key => $row) {
                $k = $key + 1;
                $rows['id'] = $k;
                $rows['store_id'] = $row["store_id"];
                $rows['name'] = $row['name'];
                $rows['storename'] = $row['storename'];
                $rows['tel'] = $row['tel'];
                $rows['address'] = $row["front_province"] . $row["front_city"] . $row["front_area"] . $row["front_address"];
                $rows['status'] = Data::$_store_business_status[$row['business_status']];
                echo implode("\t ,", $rows) . "\n";
            }

            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:text/csv');
            $log = array();
            $log['table_id'] = 0;
            $log['table_name'] = 'care';
            $log['type'] = 5;
            $log['page'] = $tableName;
            $log['content'] = $log['page'] . "：" . $tableName . ".csv";
            $org = array();
            $modify = array();
            $this->model->setLog($log, $org, $modify);
            exit;
        }else{
            Tools::AlertTxt('?md=manage&cl=store&at=storelist', '没有可汇出数据');
        }
    }


}
